<?php
namespace app\common\service;
use OSS\Credentials\StaticCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
use think\facade\Env;
class OssService
{
    public $client;

    public function __construct()
    {

               // 获取AK和SK信息
               $accessKeyId =  Env::get('aliyun_oss.access_key_id');;
               $accessKeySecret =  Env::get('aliyun_oss.access_key_secret');;
                // 从环境变量中获取访问凭证,并保存在provider中。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
                $provider = new StaticCredentialsProvider($accessKeyId,$accessKeySecret);
                $endpoint =  Env::get('aliyun_oss.endpoint');
                $config = array(
                    "provider" => $provider,
                    "endpoint" => $endpoint,
                    "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
                    "region"=> Env::get('aliyun_oss.region'),
                );
                $ossClient = new OssClient($config);
                $this->client = $ossClient;


    }
    //下载oss
    //$object 填写不包含Bucket名称在内的Object完整路径，例如testfolder/exampleobject.txt。
    //$localfile 本地路径
    public function downloadOss($object,$localfile)
    {

            $local = ROOT_PATH . '/public' .$localfile;
            $bucket = Env::get('aliyun_oss.bucket');
            $options = array(
                OssClient::OSS_FILE_DOWNLOAD => $local
            );
            $this->client->getObject($bucket, $object, $options);
            return [

                    'local'=>$localfile,
                    'path'=>$local,

            ];
    }
    //$object 填写不包含Bucket名称在内的Object完整路径，例如testfolder/exampleobject.txt。
    //$content 文件内容
    public function uploadOss($object,$content)
    {

        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        //$object = "exampledir/exampleobject.txt";
        // 填写待上传的字符串。
        //$content = "Hello OSS";
        $bucket = Env::get('aliyun_oss.bucket');
        // 上传时可以设置相关的headers，例如设置访问权限为private、自定义元数据等。
        $options = array(
            OssClient::OSS_HEADERS => array(
                'x-oss-object-acl' => 'private',
                'x-oss-meta-info' =>  Env::get('aliyun_oss.auth_key'),
            ),
        );

        $this->client->putObject($bucket, $object, $content, $options);

    }
}